package com.demo.common.redis.delay;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 在容器启动后处理 redis 的延迟消息订阅对象(pub/sub方式)
 * </p>
 *
 * @author molong
 * @date 2022/6/22
 */
public class DelayMessageApplicationStartedEvent implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        DelayMessageListenerContainer container = SpringUtil.getBean(DelayMessageListenerContainer.class);
        container.setRedisSerializer(SpringUtil.getBean(RedisSerializer.class));

        Map<String, DelayMessageListener> beansOfType = SpringUtil.getBeansOfType(DelayMessageListener.class);
        List<DelayMessageListener> values = new ArrayList<>(beansOfType.values());
        for (DelayMessageListener value : values) {
            container.register(value);
        }
        //启动监听容器
        container.start();
    }
}
